import G6, { IGroup, Item, ModelConfig } from '@antv/g6'
import { getShapePosition } from './tool';
// 自定义节点
export const registerNode = (nodeName: string, extendedNodeName: string) => {
    G6.registerNode(
        nodeName,
        {
            afterDraw(cfg, group:  IGroup | undefined) {
                const box = group?.getBBox() // 获取包围盒的坐标和尺寸
                const anchorPoints = this.getAnchorPoints(cfg) // 获取节点的锚点
                // 添加锚点
                anchorPoints.forEach((item:[number,number], index: number) => {
                    group?.addShape('circle', {
                        attrs: {
                            r: 5,
                            x: box.x + box.width * item[0],
                            y: box.y + box.height * item[1],
                            fill: '#fff',
                            stroke: '#5F95FF'
                        },
                        name: `node-shape`, // 名称
                        anchorPointIdx: index, // 锚点的索引
                        visible: false,// 是否显示
                        links: 0, // 边数
                        draggable: true, // 允许拖拽
                        cursor: 'pointer',// 鼠标样式
                    })
                });
            },
            getAnchorPoints(cfg:ModelConfig | undefined){
                return cfg?.anchorPoints || getShapePosition(cfg?.type as string)
            },
            // 设置节点的状态
            setState(name?:string, value?:string | boolean | undefined, item?:Item | undefined) {
                if (name === 'showAnchors') {
                    // 获取所有的锚点
                    const anchorPoints = item?.getContainer().findAll((ele: { get: (arg0: string) => string; }) => ele.get('name') === 'node-shape');
                    anchorPoints?.forEach((point: any) => {
                        if (value || point.get('links') > 0) point.show()
                        else point.hide()
                    })
                }
                
            },
        },
        extendedNodeName,
    );
}
